<?php

namespace App\Admin\Controllers;

use App\Admin\Extensions\Action\LatLngImport;
use App\Http\Traits\GlobalConstant;
use App\Models\Project;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Illuminate\Support\Facades\Validator;

class ProjectController extends BaseController
{

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('项目列表')
            ->description(' ')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('项目详情')
            ->description(' ')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        $info           = Project::find($id);
        $_polygon       = GlobalConstant::formatCoords($info['coords']);
        $info['coords'] = GlobalConstant::changeCoords($info['coords'], true);
        $action         = url('admin/project/' . $info['id']);
        return $content
            ->header('编辑项目')
            ->description(' ')
            ->body(view('admin.project', ['info' => $info, 'action' => $action, '_polygon' => $_polygon]));
//            ->body($this->form($id)->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        $action = url('admin/project/update');
        return $content
            ->header('新增项目')
            ->description('新增项目')
//            ->body($this->form());
            ->body(view('admin.project', ['action' => $action]));
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Project());
        $grid->filter(function ($filter) {
            // 去掉默认的id过滤器
            $filter->disableIdFilter();
            $filter->column(1 / 2, function ($filter) {
                $filter->like('name', '项目名称');
                $filter->like('address', '项目地址');
                $filter->like('leader', '负责人');
            });
            $filter->column(1 / 2, function ($filter) {
                $filter->like('center_pos', '中心位置');
                $filter->like('leader_phone', '负责人手机');
                $filter->equal('state', '状态')->select(GlobalConstant::PROJECT_STATUS);
            });

        });
//
        $grid->model()->orderBy('id', 'desc');

        $grid->column('id', '项目ID')->sortable();
        $grid->column('name', '项目名称');
        $grid->column('desc', '描述')->limit(50);
        $grid->column('address', '项目地址');
        $grid->column('center_pos', '中心位置');
        $grid->column('leader','负责人');
        $grid->column('leader_phone','负责人手机');
//        $grid->column('centrality', '中心点坐标')->display(function () {
//            return $this->lng . ',' . $this->lat;
//        });
        $grid->column('state', '状态')->label([1 => 'primary', 2 => 'danger']);
//        $grid->column('state', '状态')->display(function ($v) {
//            return GlobalConstant::PROJECT_STATUS[$v];
//        })->label([1 => 'primary', 2 => 'danger']);
        $grid->column('created_at', '创建时间');
        $grid->actions(function ($actions) {
            $actions->disableView();

        });
        $grid->disableBatchActions();
        $grid->tools(function ($tools) {
//            $tools->append(new LatLngImport());
            $tools->batch(function ($batch) {
                $batch->disableDelete();
            });
        });
        $grid->expandFilter();
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Project::findOrFail($id));

        $show->field('created_at', '下单时间');
        $show->panel()
            ->tools(function ($tools) {
                $tools->disableDelete();
                $tools->disableEdit();
            });
        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form($id = 0)
    {
        $form = new Form(new Project());
        $form->column(1 / 2, function ($form) {
            $form->display('id', '项目ID');
            $form->text('name', '项目名称')->required();
            $form->text('desc', '项目描述')->required();;
            $form->text('leader', '项目负责人')->required();;
            $form->mobile('leader_phone', '负责人手机')->required();;
//            $form->latlong('lat', 'lng', '中心点位置')->zoom(10)->default(['lat' => 29.56900, 'lng' => 106.55844])->height(500);
            $form->radio('status', '状态')->options([0 => '禁用', 1 => '正常'])->default(1);
            $form->radio('state', '项目状态')->options(GlobalConstant::PROJECT_STATUS)->default(1);
        });
        $form->column(1 / 2, function ($form) {

            $form->list('coords', '地图坐标集')->default([]);
        });

        $form->tools(function (Form\Tools $tools) {
            // 去掉`删除`按钮
            $tools->disableDelete();
            $tools->disableView();
        });
        $form->footer(function ($footer) {
            // 去掉`查看`checkbox
            $footer->disableViewCheck();
            // 去掉`继续编辑`checkbox
            $footer->disableEditingCheck();
            // 去掉`继续创建`checkbox
            $footer->disableCreatingCheck();
            $footer->disableReset();
        });
        return $form;
    }

    public function update($id = 0)
    {
        $data      = request()->input();
        $validator = Validator::make($data, [
            'name'         => ['required', 'max:50'],
            'desc'         => ['required'],
            'lat'          => ['required'],
            'lng'          => ['required'],
            'leader'       => ['required'],
            'leader_phone' => ['required'],
            'coords'       => ['required'],
        ], [
            'name.required'         => '项目名称不能为空',
            'name.max'              => '项目名称不能超过100个字',
            'desc.required'         => '项目描述不能为空',
            'lat.required'          => '项目中心点不能为空',
            'lng.required'          => '项目中心点不能为空',
            'leader.required'       => '项目负责人不能为空',
            'leader_phone.required' => '项目负责人手机不能为空',
            'coords.required'       => '项目区域不能为空',
        ]);
        if ($validator->fails()) {
            return back()->withErrors($validator->errors()->first());
        }
        unset($data['_token']);
        unset($data['_method']);
        $data['coords'] = GlobalConstant::changeCoords($data['coords']);
        try {
            if (empty($id)) {
                Project::create($data);
            } else {
                Project::where('id', $id)->update($data);
            }
        } catch (\Exception $exception) {
            return back()->withErrors($exception->getMessage());
        }
        return redirect('admin/project');
    }


}
